'use strict';

import React from 'react';
import {
    StyleSheet,
    Text,
    View,
    ScrollView,
    Image,
    InteractionManager,
    NativeModules,
    ListView,
    TouchableHighlight,
    Modal,
    RefreshControl,
    Alert,
    TouchableOpacity,
    FlatList,
    Dimensions
} from 'react-native';
import {connect} from 'react-redux';
import {
    getShopInfo,
    showQrImg,
    hideQrImg,
    changeRefresh,
    showModels,
    getToken,
    gotoAddProduct,
    getTrade,
    // getSummary
} from './actions';
import NaviUtil from '../../utils/NaviUtil';
import Communications from 'react-native-communications';
import {authShops} from '../shop/actions';
import NavBarCommon from '../../component/NavBarCommon';
import QRCode from 'react-native-qrcode';
import {BarChart, YAxis, XAxis} from 'react-native-svg-charts';
import ShopState from './shopState';
import themeconfig from '../../config/theme';

import {naviPush} from '../../navigatorApp/actions';
import moment from 'moment';
import {paddingBottom} from '../../utils/ScreenUtil';

let {width, height} = Dimensions.get('window');

class Main2 extends React.Component {

    static navigationOptions = ({navigation, screenProps}) => ({
        header: null,
    });

    constructor(props) {
        super(props);

        this.page = 1;
        this.size = 10

        this.state = {
            type: 'year',
            summary: [0],
            shopImgModalVisible: false,
            datasource: [],
            isLoading: false,
            footText: "",
            hasMore: false,
        };
    }

    componentDidMount() {
        InteractionManager.runAfterInteractions(() => {
            this.getShops();
        });
    }


    getShops = () => {
        const self = this;
        authShops(function (token, user) {
            // self.getSummary(token);
            self.getTrade(token);
            self.props.getToken(token, user);
            self.props.getShopInfo();
        });
    };

    // getSummary = (token) => {
    //     const self = this;
    //     let value = 0;
    //     if (self.state.type == 'month') {
    //         value = moment().month() + 1;
    //     } else {
    //         value = moment().year();
    //     }
    //     getSummary(token, self.state.type, value, (data) => {
    //         console.log(data);
    //         let summary = [];
    //         let value = 0
    //         if (self.state.type == 'month') {
    //             value = moment().daysInMonth();
    //         } else {
    //             value = 12;
    //         }
    //         for (let i = 1; i <= value; i++) {
    //             let has = false;
    //             data.forEach(element => {
    //                 if (element.time == i) {
    //                     has = true;
    //                     summary.push(element.amount / 100);
    //                 }
    //             });
    //             if (!has) {
    //                 summary.push(0);
    //             }
    //         }
    //         self.setState({summary: summary});
    //     });
    // }

    getTrade = (token) => {
        const self = this;
        getTrade(token, self.page, self.size, (data) => {
            let newdata = self.state.datasource;
            if (self.page != 1) {
                newdata = newdata.concat(data);
            } else {
                newdata = data;
            }
            if (data.length < self.size) {
                self.setState({
                    isLoading: false,
                    refreshing: false,
                    hasMore: false,
                    footText: '加载完成',
                    datasource: newdata
                })
            } else {
                self.setState({
                    isLoading: false,
                    refreshing: false,
                    hasMore: true,
                    footText: '加载更多',
                    datasource: newdata
                })
            }
        });
    }

    refreshData = () => {
        const self = this;
        return function () {
            self.getShops();
        }
    };

    isCanUse = () => {
        if (this.props.shopState == 2) {
            return true;
        } else if (this.props.shopState == 3) {
            Alert.alert('提示',
                "您的店铺正在审核中",
                [
                    {
                        text: '了解', onPress: () => {
                    }
                    },
                ]);
        } else {
            let tsMessage = "";
            let buttonTitle = "";
            if (this.props.shopState == 0) {
                tsMessage = "请先创建店铺";
                buttonTitle = "立即创建";
            } else if (this.props.shopState == 1) {
                tsMessage = "请先完善店铺";
                buttonTitle = "立即完善";
            }
            Alert.alert('提示',
                tsMessage,
                [
                    {
                        text: '以后再说', onPress: () => {
                    }
                    },
                    {
                        text: buttonTitle, onPress: () => {
                        this.props.naviPush("shopComplete")
                    }
                    }
                ]);
            return false;
        }
    }

    moduleOnClick = (item, passProps, navigator) => {
        if (this.isCanUse()) {
            this.props.gotoAddProduct(false);
            this.props.naviPush(item.tag)
        }
    };

    showQrImg = () => {
        if (this.isCanUse()) {
            this.setState({
                shopImgModalVisible: !this.state.shopImgModalVisible
            })
        }
    };

    renderItem = (item) => {
        let trade = item.item;
        return <View style={{flexDirection: 'row', alignItems: 'center', padding: 10}}>
            <Image style={{width: 40, height: 40, borderRadius: 20}} source={{uri: trade.userPhoto || ''}}/>
            <View style={{flex: 1, marginHorizontal: 10}}>
                <Text style={{fontSize: 16}}>{trade.userName}</Text>
                <Text style={{color: 'darkgray', marginTop: 5}}>{trade.createdAt}</Text>
            </View>
            <Text style={{color: themeconfig.maincolor, fontSize: 20}}>+{trade.totalAmount / 100}</Text>
        </View>
    }

    renderSeparator = () => {
        return (<View style={{height: 1, backgroundColor: '#eee'}}></View>)
    }

    renderEmpty = () => {
        return (<View style={{height: 100, justifyContent: 'center', alignItems: 'center'}}>
            <Image style={{width: 80, height: 80}} source={require('../../image/nodata.png')}/>
        </View>)
    }

    renderFooter = () => {
        return (
            <View style={{
                padding: 10,
                borderTopColor: "#eee",
                borderTopWidth: 1,
                flex: 1,
                flexDirection: 'row',
                justifyContent: 'center'
            }}>
                <Text style={{color: "gray"}}>{this.state.footText}</Text>
            </View>
        )
    }

    onEndReached = () => {
        if (this.state.hasMore && !this.state.isLoading) {
            this.page = this.page + 1;
            this.setState({isLoading: true});
            this.getTrade();
        }
    }

    render() {
        let qrurl = "http://wap.tianyihui1688.com/shop/info" + "?" + "id=" + this.props.shopInfo.shopid + "&action=pay";

        const fill = 'rgb(134, 65, 244)';
        const data = this.state.summary;

        let tradeHeight = this.state.datasource.length * 61;
        if (tradeHeight == 0) {
            tradeHeight = 100;
        }

        const transactionMonthValue = parseInt(this.props.shopData.transactionMonth) / 100;
        const transactionAllValue = parseInt(this.props.shopData.transactionAll) / 100;

        return <View
            style={{flex: 1, flexDirection: 'column', justifyContent: 'space-between', marginBottom: paddingBottom}}>
            <NavBarCommon title='首页' leftImage={require('../../image/mine.png')} leftAction={() => {
                this.props.naviPush('Mine');
            }} rightImage={require('../../image/qr.png')} rightAction={() => {
                this.showQrImg();
            }}/>
            <ScrollView
                contentContainerStyle={{backgroundColor: "#eeeeee", paddingHorizontal: 10}}
                refreshControl={
                    <RefreshControl
                        refreshing={this.props.refreshLoading}
                        onRefresh={this.refreshData()}
                    />
                }>
                <ShopState/>
                <View style={{flexDirection: 'row', padding: 10, backgroundColor: 'white', borderRadius: 5, marginTop: 10}}>
                    <View style={{flex: 1, padding: 10}}>
                        <View style={{height: (width - 80) / 4, backgroundColor: '#b2eeef', justifyContent: 'center', alignItems: 'center', borderRadius: 5}}>
                            <Text style={{fontSize: 18, color: 'white'}}>¥{transactionMonthValue}</Text>
                        </View>
                        <Text style={{marginTop: 10, fontSize: 18, color: '#474747', textAlign: 'center'}}>今日流水</Text>
                    </View>
                    <View style={{flex: 1, padding: 10}}>
                        <View style={{height: (width - 80) / 4, backgroundColor: '#b2eeef', justifyContent: 'center', alignItems: 'center', borderRadius: 5}}>
                            <Text style={{fontSize: 18, color: 'white'}}>¥{transactionAllValue}</Text>
                        </View>
                        <Text style={{marginTop: 10, fontSize: 18, color: '#474747', textAlign: 'center'}}>总流水</Text>
                    </View>
                </View>

                <View style={{
                    flexWrap: 'wrap',
                    flexDirection: 'row',
                    backgroundColor: 'white',
                    padding: 10,
                    marginTop: 10,
                    borderRadius: 5
                }}>
                    <TouchableOpacity style={{width: (width - 40) / 3, marginVertical: 10, justifyContent: 'center', alignItems: 'center'}} onPress={() => {
                        this.props.naviPush('product', {catCode: '001', catId: 56});
                    }}>
                        <Image style={{width: 50, height: 50}} source={require('../../image/pet.png')}/>
                        <Text style={{fontSize: 15, marginTop: 10, color: '#6e6e6e'}}>宠物管理</Text>
                    </TouchableOpacity>
                    <TouchableOpacity style={{width: (width - 40) / 3, marginVertical: 10, justifyContent: 'center', alignItems: 'center'}} onPress={() => {
                        this.props.naviPush('product', {catCode: '002', catId: 6});
                    }}>
                        <Image style={{width: 50, height: 50}} source={require('../../image/goods.png')}/>
                        <Text style={{fontSize: 15, marginTop: 10, color: '#6e6e6e'}}>商品管理</Text>
                    </TouchableOpacity>
                    <TouchableOpacity style={{width: (width - 40) / 3, marginVertical: 10, justifyContent: 'center', alignItems: 'center'}} onPress={() => {
                        this.props.naviPush('product', {catCode: '003', catId: 100});
                    }}>
                        <Image style={{width: 50, height: 50}} source={require('../../image/home_service.png')}/>
                        <Text style={{fontSize: 15, marginTop: 10, color: '#6e6e6e'}}>服务管理</Text>
                    </TouchableOpacity>
                    <TouchableOpacity style={{width: (width - 40) / 3, marginVertical: 10, justifyContent: 'center', alignItems: 'center'}} onPress={() => {
                        this.props.naviPush('income');
                    }}>
                        <Image style={{width: 50, height: 50}} source={require('../../image/money.png')}/>
                        <Text style={{fontSize: 15, marginTop: 10, color: '#6e6e6e'}}>现金管理</Text>
                    </TouchableOpacity>
                    <TouchableOpacity style={{width: (width - 40) / 3, marginVertical: 10, justifyContent: 'center', alignItems: 'center'}} onPress={() => {
                        this.props.naviPush('shop');
                    }}>
                        <Image style={{width: 50, height: 50}} source={require('../../image/home_shop.png')}/>
                        <Text style={{fontSize: 15, marginTop: 10, color: '#6e6e6e'}}>店铺管理</Text>
                    </TouchableOpacity>
                    <TouchableOpacity style={{width: (width - 40) / 3, marginVertical: 10, justifyContent: 'center', alignItems: 'center'}} onPress={() => {
                        this.props.naviPush('Order');
                    }}>
                        <Image style={{width: 50, height: 50}} source={require('../../image/myorder.png')}/>
                        <Text style={{fontSize: 15, marginTop: 10, color: '#6e6e6e'}}>我的订单</Text>
                    </TouchableOpacity>
                </View>
                <View style={{
                    backgroundColor: 'white',
                    paddingTop: 10,
                    marginTop: 10,
                    marginBottom: 10,
                    borderRadius: 5
                }}>
                    <View style={{flexDirection: 'row', justifyContent: 'space-between', backgroundColor: '#ffffff00', marginTop: -35, borderRadius: 5, paddingHorizontal: 40}}>
                        <Image style={{width: 10, height: 45}} source={require('../../image/peishi.png')}/>
                        <Image style={{width: 10, height: 45}} source={require('../../image/peishi.png')}/>
                        <Image style={{width: 10, height: 45}} source={require('../../image/peishi.png')}/>
                    </View>
                    <View style={{flexDirection: 'row', alignItems: 'center', padding: 10}}>
                        <View style={{backgroundColor: themeconfig.maincolor, width: 5, height: 20}}/>
                        <Text style={{fontSize: 20, marginLeft: 10}}>交易记录</Text>
                    </View>
                    <FlatList
                        style={{height: tradeHeight, marginTop: 10}}
                        scrollEnabled={false}
                        ItemSeparatorComponent={this.renderSeparator}
                        data={this.state.datasource}
                        renderItem={this.renderItem}
                        ListFooterComponent={this.renderFooter}
                        // onEndReached={this.onEndReached}
                        // onEndReachedThreshold={0}
                        ListEmptyComponent={this.renderEmpty}
                    />
                </View>
            </ScrollView>
            <Modal
                transparent={true}
                visible={this.state.shopImgModalVisible}
                onRequestClose={() => this.showQrImg()}>
                <TouchableHighlight
                    underlayColor='rgba(255,255,255,0)'
                    style={{
                        flex: 1
                    }}
                    onPress={() => this.showQrImg()}>
                    <View
                        style={{
                            backgroundColor: 'rgba(0,0,0,0.8)',
                            flex: 1,
                            flexDirection: 'column',
                            alignItems: 'center',
                            justifyContent: 'center'
                        }}>
                        <View style={{
                            borderRadius: 5,
                            flexDirection: 'column',
                            backgroundColor: 'white',
                            alignItems: 'center',
                            justifyContent: 'center',
                            width: 220,
                            height: 320
                        }}>
                            <Text
                                style={{
                                    marginTop: 20,
                                    fontStyle: 'italic',
                                    fontSize: 18,
                                    marginBottom: 20
                                }}>{this.props.shopInfo.shopname}</Text>
                            <QRCode
                                value={qrurl}
                                size={180}
                                bgColor='black'
                                fgColor='white'/>
                        </View>
                    </View>
                </TouchableHighlight>
            </Modal>
        </View>
    }
}

const mapStateToProps = (state) => {
    return {
        shopState: state.mainmodel.shopState,
        models: state.mainmodel.models,
        shopInfo: state.mainmodel.shopInfo,
        shopData: state.mainmodel.shopData,
        isloading: state.mainmodel.isloading,
        shopImgModalVisible: state.mainmodel.shopImgModalVisible,
        refreshLoading: state.mainmodel.refreshLoading,
        token: state.mainmodel.token,
        userToken: state.mainmodel.userToken
    }
}

const mapDispatchToProps = (dispatch) => {
    return {
        naviPush: (routerName, params) => {
            dispatch(naviPush(routerName, params))
        },
        getShopInfo: () => {
            dispatch(getShopInfo())
        },
        hideQrImg: () => {
            dispatch(hideQrImg())
        },
        showModels: () => {
            dispatch(showModels())
        },
        getToken: (token, usertoken) => {
            dispatch(getToken(token, usertoken))
        },
        gotoAddProduct: (value) => {
            dispatch(gotoAddProduct(value));
        }
    }
};

export default connect(
    mapStateToProps,
    mapDispatchToProps,
)(Main2);